﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Db4objects.Db4o;

namespace MyToolkit.Com
{
    public class Entity<T> where T : Entity<T>, new()
    {
        public Guid ID { get; private set; }

        public static T Create()
        {
            return new T() { ID = Guid.NewGuid() };
        }

        public static T QuerySingle(Guid id)
        {
            using (var db = Open())
            {
                return db.Query<T>(o => o.ID == id).SingleOrDefault();
            }
        }

        public static T QuerySingle(Func<T, bool> predicate)
        {
            using (var db = Open())
            {
                return db.Query<T>().Where(predicate).SingleOrDefault();
            }
        }

        public static List<T> Query(Func<T, bool> predicate)
        {
            using (var db = Open())
            {
                return db.Query<T>().Where(predicate).ToList();
            }
        }

        public static List<T> GetAll()
        {
            using (var db = Open())
            {
                return db.Query<T>().ToList();
            }
        }

        public void Save()
        {
            if (this.ID == null)
            {
                this.ID = Guid.NewGuid();
            }

            using (var db = Open())
            {
                db.Store(this);
                db.Commit();
            }
        }

        public void Remove()
        {
            if (this.ID == null)
            {
                throw new Exception("ID can not be empty.");
            }
            using (var db = Open())
            {
                db.Delete(this);
                db.Commit();
            }
        }

        protected static IEmbeddedObjectContainer Open()
        {
            return Db4oEmbedded.OpenFile(System.IO.Directory.GetCurrentDirectory() + "/db.yap");
        }
    }
}
